/**
 * Created by Alice on 2016/9/22 0022
 */

var planUid = utils.get_url_param("planUid");
var ip = null;
var channel = utils.get_url_param("channel");	//通道号
var videoNum = utils.get_url_param("videonum") || 0;	//录像号
var _data;//获取播放视频列表数据
var now_video = utils.get_url_param('vlcCourtUid');

$(function () {
    $("#imageLoad").attr("href", r.base_path + 'my/screenshot');
    //获取笔录信息
    getCourtrecForId();
    getCaseInfoByIdForToday();
    $("#_nav_court_info").click(function () {
        $("#_nav_court_p").attr("class", "");
        $("#_nav_court_note").attr("class", "");
        $("#_nav_court_info").attr("class", "active");
        $("#_court_info").show();
        // $("#_court_case").hide();
        $("#_court_note").hide();
        $("#_nav_court_note_down").hide();
    });
    $("#_nav_court_note").click(function () {
        $("#_nav_court_info").attr("class", "");
        $("#_nav_court_p").attr("class", "");
        $("#_nav_court_note").attr("class", "active");
        $("#_court_info").hide();
        $("#_court_note").show();
        $("#_nav_court_note_down").show();
    });
    $("#_nav_court_p").click(function () {
        $("#_nav_court_p").attr("class", "active");
        $("#_nav_court_note").attr("class", "");
        $("#_nav_court_info").attr("class", "");
        $("#_court_info").hide();
        $("#_court_note").hide();
    });

    $("#channels").change(function () {
        var now = vlc.input.time;
        channelChange();

        // doPlayOrPause();
        // window.setTimeout(doPlayOrPause, 500);
    });

    $("#videos").change(function () {
        play_video($("#videos").val());
    });

});

function getCaseInfoByIdForToday() {
    var caseInfo = caseMap;
    var archives = caseInfo.archives;
    var caseName = caseInfo.caseName;
    //记录案件名称、案号，并向后台发送点播信息
    playRecordinfo();
    var caseTypeName = caseInfo.casetypeName;
    var judge_user_uid = caseInfo.judgeUserUid;
    var secretary_uid = caseInfo.secretaryUserUid;
    var courtroomName = caseInfo.courtRoomName;
    var statusName = caseInfo.statusName;
    var parties = caseInfo.accuse + " " + caseInfo.accused;
    var startDate = caseInfo.startDate;
    var planDate = caseInfo.planDate;
    var endDate = caseInfo.endDate;
    var caseDesc = caseInfo.casedesc || "";
    var title_text = '&nbsp;' + archives + '——' + caseName;
    if (title_text.length > 50) {
        title_text = title_text.substring(0, 50) + '...';
    }
    $("#title").html(title_text);
    var html = ['  <div class="cmp-play-text">',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案  号：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + archives + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案件类型：</span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-8 text-left">',
        '                                <span>' + caseTypeName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>案件名称：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + caseName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>审判长：</span>',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                                <span><a id="judge_name" class="white-a">' + (caseInfo.judgeName ? caseInfo.judgeName : '') + '</a></span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>书记员：</span>',
        '                            </div>',
        '                            <div class="col-md-3  col-xs-8 text-left">',
        '                                <span><a id="secretary_name" class="white-a">' + (caseInfo.secretaryName ? caseInfo.secretaryName : '') + '</a></span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>当事人：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + parties + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>开庭地点：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + (courtroomName ? courtroomName : '') + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>排期时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + planDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>开庭时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + startDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>闭庭时间：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + endDate + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>庭审状态：</span>',
        '                            </div>',
        '                            <div class="col-md-3 col-xs-8 text-left">',
        '                                <span>' + statusName + '</span>',
        '                            </div>',
        '                        </div>',
        '                        <div class="row row-court">',
        '                            <div class="col-md-3 col-xs-4 text-right">',
        '                                <span>基本案情：</span>',
        '                            </div>',
        '                            <div class="col-md-9 col-xs-8 text-left">',
        '                                <span>' + caseDesc + '</span>',
        '                            </div>',
        '                        </div>',
        '                    </div>'].join("");
    $("#_court_info").append(html);
    $("#judge_name").attr("href", judge_user_uid?r.base_path + "more/more_review?judge=" + judge_user_uid + "&city=" + now_video + '&courtUid=' + r.court_uid:'javascript:void(0);');
    $("#secretary_name").attr("href", secretary_uid?r.base_path + "more/more_review?secretary=" + secretary_uid + "&city=" + now_video + '&courtUid=' + r.court_uid:'javascript:void(0);');
    $("#loading").hide();
    getInfo();
}

/**
 * 获取点播信息
 */
function getInfo() {
    $.ajax({
        url: r.base_path + "video/selectPlayVideo",
        type: 'post',
        async: false,
        dataType: "json",
        data: {
            trialUid: trialUid,
            courtUid: now_video
        },
        success: function (result) {
            $("#loading").hide();
            if (result.code == 0) {
                if (!result.data) {
                    alert("没有找到点播信息！");
                    return;
                }
                //result.data赋值给_data 以后操作_data
                _data = result.data;
                var chn = [];
                //构造点播通道select
                $.each(_data, function (i, n) {
                    if (chn.indexOf(n.channelsName) == -1) {
                        $("#channels").append("<option value='" + n.channelsName + "'>" + n.channelsName + "</option>");
                        chn.push(n.channelsName);
                    }

                    if (n.startRecTime) {
                        var startRecTime = new Date(n.startRecTime);
                        n.startRecTime = (startRecTime.getHours() > 9 ? startRecTime.getHours() : "0" + startRecTime.getHours()) + ":" + (startRecTime.getMinutes() > 9 ? startRecTime.getMinutes() : "0" + startRecTime.getMinutes());
                    } else {
                        n.startRecTime = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    }
                    if (n.endRecTime) {
                        var endRecTime = new Date(n.endRecTime);
                        n.endRecTime = (endRecTime.getHours() > 9 ? endRecTime.getHours() : "0" + endRecTime.getHours()) + ":" + (endRecTime.getMinutes() > 9 ? endRecTime.getMinutes() : "0" + endRecTime.getMinutes());
                    } else {
                        n.endRecTime = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    }
                });
                //获取url的点播通道号进行选中点播通道的select，如果为空则初始化
                if (channel == null && $("#channels>option").length != 0) {
                    channel = 1;
                } else {
                    $("#channels>option").eq(channel).attr("selected", "selected");
                }
                console.log('change')
                //调用方法进行构造点播录像select
                channelChange(videoNum);
                //尝试获取url中点播的视频编号进行选中点播录像select，如果为空则初始化
                $("#videos>option:eq(" + parseInt(videoNum) + ")").attr("selected", "selected");

            } else {
                console.log(result.msg);
            }
        }
    });
}

function channelChange(num) {
    num = num || 0;
    channel = $("#channels").val();
    var i = 0;
    //清空select
    $("#videos").html("");
    $.each(_data, function (j, n) {
        var temp = $("#channels").val();
        if (n.channelsName == temp) {
            $("#videos").append("<option value=\"" + i + "\">" + n.startRecTime + "—" + n.endRecTime + "</option>");
            i++;
        }
    });
    console.log(num, channel, _data);
    vlc_playlist = [];
    $.each(_data, function (i, n) {
        if (n.channelsName == channel) {
            vlc_playlist.push(n);
        }
    });
    init_playlist(num);
}

/**
 * 根据id查询笔录信息
 * @param planUid
 */
function getCourtrecForId() {
    $.post(r.base_path + "video/courtrecForId", {trialUid: trialUid, courtUid: now_video}, function (result) {
        if (result && result.data) {
            $("#notetext").html(result.data[0]);
            //绑定笔录下载地址--基于http下载
            $("#noteLoad").attr("href", result.data[1]);
        }
    });
}

//单个文件下载
function down() {
    //获取当前选中的通道图像
    var name = $("#channels").find("option:selected").text();
    if (!name) {
        return;
    }
    //根据图像名称，获取这个通道图像的所有视频
    var channel_data = [];
    $.each(_data, function (j, n) {
        if (n.channelsName == name) {
            //拼接真实下载地址
            channel_data.push(n.downloadUrl);
        }
    });
    //真实模拟(多视频文件下载)
    if (channel_data.length > 0) {
        //测试使用
        //var downloadUrl = ['http://localhost:8080/ssm/videos/2.mp4','http://localhost:8080/ssm/videos/1.mp4'];
        // var downloadUrl = channel_data;
        //页面动态生成a标签，模拟用户多个点击事件
        //清空原来下面的a标签
        $("#table").empty();
        $.each(channel_data, function (index, ele) {
            var count = parseInt(index, 0) + 1;
            var tr = "<tr><td style='border:1px solid blue;text-align:center;height:40px;'><a download  style='font-size:20px;text-decoration:underline;'  id='" + index + "'href='" + ele + "'>" + name + "_" + count + ".mp4</a></td></tr>";
            //放在页面上，触发点击事件
            $("#table").append(tr);
            //触发点击事件
            //document.getElementById(""+index).click();
        });
        //先绑定数据到模态框上面
        /* 完成拖拽 */
        $("#download_video").draggable({
            cursor: "move",
            handle: '.modal-header'//--指定只有拖拽头部，才能拖拽
        });
        //显示模态框
        $("#download_video").modal("show");

    }
}

function formatTime(timeVal) {
    if (typeof timeVal != 'number')
        return "-:--:--";
    var timeHour = Math.round(timeVal / 1000);
    var timeSec = timeHour % 60;
    if (timeSec < 10)
        timeSec = '0' + timeSec;
    timeHour = (timeHour - timeSec) / 60;
    var timeMin = timeHour % 60;
    if (timeMin < 10)
        timeMin = '0' + timeMin;
    timeHour = (timeHour - timeMin) / 60;
    if (timeHour > 0)
        return timeHour + ":" + timeMin + ":" + timeSec;
    else
        return timeMin + ":" + timeSec;
}

//抓怕函数
function catch1() {
    //获取当前毫秒数
    var currentTimeMills = doGetPosition();
    //转成秒数
    var time = parseInt(currentTimeMills / 1000);
    //请求后台真真的抓拍功能
    catchImage(time);
}

function doGetPosition() {
    return vlc.input.time;
}

function formatTime1(value) {
    var theTime = parseInt(value / 1000);// 秒
    var theTime1 = 0;// 分
    var theTime2 = 0;// 小时
    if (theTime > 60) {
        theTime1 = parseInt(theTime / 60);
        theTime = parseInt(theTime % 60);
        if (theTime1 > 60) {
            theTime2 = parseInt(theTime1 / 60);
            theTime1 = parseInt(theTime1 % 60);
        }
    }
    var result = "" + parseInt(theTime) + "秒";
    if (theTime1 > 0) {
        result = "" + parseInt(theTime1) + "分" + result;
    }
    if (theTime2 > 0) {
        result = "" + parseInt(theTime2) + "小时" + result;
    }
    return result;
}

var start = '';
var end = '';
//刷新清空当前数据
$("#startText").val('');
$("#endText").val('');

function start1() {
    var position = doGetPosition();
    start = parseInt(position / 1000);
    $("#startText").val(formatTime1(position));
}

function end1() {
    var position = doGetPosition();
    end = parseInt(position / 1000);
    $("#endText").val(formatTime1(position));
}

function catchImage(time) {
    var now_url = vlc_playlist[now_playing].playUrl;
    console.info(now_url);
    document.getElementById("catch1").disabled = true;
    $.ajax({
        "type": "post",
        "url": r.base_path + 'image/catchImage?t=' + new Date().getTime(),
        "dataType": "json",
        "data": {
            time: time,
            url: now_url,
            planUid: planUid
        },
        "success": function (result) {
            if (result&&result.code==0) {
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg('抓拍成功');
                });
                var date = new Date();
                var d = result.data;
                var url = "http://" + location.hostname + ":8080/cmpImages/images/";
                url = url + date.getFullYear() + "/" + (date.getMonth() + 1) + "/" + d.name;
                //先绑定图片到模态框上面
                $("#image").attr("src", url);

                /* 完成拖拽 */
                $("#myModal").draggable({
                    cursor: "move"
                    //handle: '.modal-header'--指定只有拖拽头部，才能拖拽
                });
                //显示模态框
                $("#myModal").modal("show");
                document.getElementById("catch1").disabled = false;
            }else {
                layui.use('layer', function(){
                    var layer = layui.layer;
                    //边缘弹出
                    layer.open({
                        type: 1
                        ,offset: 'r' //具体配置参考：offset参数项
                        ,content: '<div style="padding: 20px 80px;">'+result.message+'</div>'
                        ,btn: '关闭'
                        ,btnAlign: 'c' //按钮居中
                        ,shade: 0 //不显示遮罩
                        ,yes: function(){
                            layer.closeAll();
                        }
                    });
                    // layer.msg(result.message);
                });
            }
        },
        "error": function () {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.open({
                    type: 1
                    ,offset: 'r' //具体配置参考：offset参数项
                    ,content: '<div style="padding: 20px 80px;">'+result.message+'</div>'
                    ,btn: '关闭'
                    ,btnAlign: 'c' //按钮居中
                    ,shade: 0 //不显示遮罩
                    ,yes: function(){
                        layer.closeAll();
                    }
                });
            });
            document.getElementById("catch1").disabled = false;
        }
    });
}

//截取函数
function subVideo() {
    var now_url = vlc_playlist[now_playing].playUrl;
    //先判断有没有开始跟结束时间
    if (start === null || start === '') {
        alert("请选择视频截取起点");
        return;
    }
    if (end === null || end === '') {
        alert("请选择视频截取终点");
        return;
    }
    if (start > end) {
        start = '';
        end = '';
        alert("截取终点时间不能小于截取起点时间!请重新开始截取");
        return;
    }
    document.getElementById("subVideo").disabled = true;
    $.ajax({
        "type": "post",
        "url": r.base_path + 'image/subVideo?' + new Date().getTime(),
        "dataType": "json",
        "data": {
            start: start,
            end: end,
            url: now_url,
            planUid: planUid
        },
        "success": function (data) {
            alert(data.message);
            document.getElementById("subVideo").disabled = false;
        },
        "error": function (data) {
            alert("视频截取失败");
            document.getElementById("subVideo").disabled = false;
        }
    });
}


//定时记录点播人员记录
function playRecordinfo() {
    var userName = $.cookie('_username');
    console.info(userName, caseMap.archives, caseMap.caseName, planUid);
    var data = {
        caseUid: caseMap.caseUid,
        userName: userName,
        courtUid: r.court_uid,
        userCourtUid: r.user_court_uid,
        planUid: planUid,
        archives: caseMap.archives,
        name: caseMap.caseName,
        type: caseMap.casetypeName,
        vod: "1"
    };
    data = JSON.stringify(data);
    create_ws(data);
}


